//
//  WBRefreshControl.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/11.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit

/// 下拉刷新控件偏移量
private let WBRefreshControlOffset: CGFloat = -60
class WBRefreshControl: UIRefreshControl {
    // MARK: - 重写系统方法
    override func endRefreshing() {
        super.endRefreshing()
        // 停止动画
        refreshView.stopAnimation()
    }
    
    /// 主动触发开始刷新动画 － 不会触发监听方法
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startAnimation()
    }
// KVO监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0 {
            return
        }
         print(frame)
        if frame.origin.y < WBRefreshControlOffset && !refreshView.rotateFlag {
            print("反过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y >= WBRefreshControlOffset && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }
      
        
    }
// MARK: - 构造函数
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
// 构建界面
    private func setupUI(){
//       1 添加控件
        addSubview(refreshView)
//       2 自动布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        addObserver(self, forKeyPath: "frame", options: [], context: nil)
    
    }
/// 删除监听方法
    deinit{
       self.removeObserver(self, forKeyPath: "frame")
    }
/// 懒加载控件
    private lazy var refreshView = WBRefreshView.refreshView()
}

/// 微博刷新视图,负责刷新动画
 class WBRefreshView:UIView{
    
    /// 旋转标记
    var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }

    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIconView: UIImageView!
    
/// 从 xib 加载视图
    class func refreshView()->WBRefreshView{
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).last as! WBRefreshView
    }
    
    private func rotateTipIcon(){
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.001 : 0.001
        
        UIView.animateWithDuration(0.5) {
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, angle)
        }
    }
    
    /// 播放加载动画
    private func startAnimation() {
        
        tipView.hidden = true
        
        // 判断动画是否已经被添加
        let key = "transform.rotation"
        if loadingIconView.layer.animationForKey(key) != nil {
            return
        }
        
        print("加载动画播放")
        
        let anim = CABasicAnimation(keyPath: key)
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = false
        
        loadingIconView.layer.addAnimation(anim, forKey: key)
    }
    /// 停止加载动画
    private func stopAnimation() {
        tipView.hidden = false
        
        loadingIconView.layer.removeAllAnimations()
    }

}
